<?php
ArrowController::importModel("org.arrowplatform.model.ArrowDataSource");
ArrowController::importModel("org.arrowplatform.controls.common.criteria.IArrowCriteriaUser"); 
ArrowController::importModel("components.smarty.SmartyCompiler");
class ArrowCtrlRepeater extends ArrowTagContainer implements IArrowCriteriaUser{
	
	protected $dataSource;
	protected $criteria;

	public function configure(){
		$this->addProperties(array(
			"dataSource" => false,
			"dsFactory" => false,
			"criteria" => false,
			"model" => false,
			"transport" => false
		));
	}
	
	public function setDataSource( IArrowDataSource $dataSource ){
		$this->dataSource = $dataSource;
	}
	
	public function setCriteria(  $criteria ){
		$_SESSION[self::CTRL_NAMESPACE][$this->getGlobalId()] = serialize($criteria);
		$this->criteria = $criteria;
	}
	
	public function getCriteria(){
		return $this->criteria;
	}
	
	
	public function init(){
		
		$res = ArrowController::$activeProject->getResources();
		//if($this->getProperty("num"))
		$this->registerJsFile( $res->getResource("/js/jquery/jquery.tablednd_0_5.js")->getRelativePath());
			
		if(is_array($this->getProperty("selected")))
			$this->setProperty("selected", implode(";", $this->getProperty("selected")));
		
		$ds = $this->getProperty("dataSource");
		$model = $this->getProperty("model");
		$dsFactory = $this->getProperty("dsFactory"); 
		$datasourceCtrl = $this->getFirstChild("ArrowCtrlDatasource");
		
		if( !empty($model)){
			$this->setDataSource( new ArrowDataSource( $model ));	
		}elseif(!empty($ds)){
			$this->setDataSource( $ds );
		}elseif(!empty($datasourceCtrl)){
			$criteria = $datasourceCtrl->getCriteria();
			$this->setDataSource( new ArrowDataSource( $criteria->getModel() ) );
			$this->setCriteria($criteria);
		}elseif(!empty( $dsFactory )){
			$ds = call_user_func( array($this->getPropertyAsModel("dsFactory"), "getNewDataSource") );
			$this->setDataSource( $ds );	
		}else{
			$parent = $this->getParent();
			if( $parent  instanceof IArrowCriteriaUser ){
				$criteria = $parent->getCriteria();
				$this->setCriteria($criteria);
				$model = $criteria->getModel();
				$this->setProperty("model", $model );
				$this->setDataSource( new ArrowDataSource( $model ));	
			}else{
				throw new ArrowException( array("msg"=> "[ArrowCtrlTable] Datasource needed") );
			}
		}
	}
	
	public function generateBlockStart(){
		$list = $this->dataSource->getList($this->criteria);
		$code = $this->getFirstChild("ArrowCtrlTemplate")->getSource();
		$compiler = new SmartyCompiler($code);
		
		
		$str = "";
		foreach($list as $el){
			$str.=$compiler->getResult(array("context" => $el, "transport" => $this->getProperty("transport")));	
		}
		return $str;
	}
	
	public function generateBlockEnd(){}
}
?>